package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Mapper.UserInfoMapper;
import com.example.demo.Mapper.UserMapper;
import com.example.demo.Mapper.QualityUserMapper;
import com.example.demo.base.ArrayCountUtils;
import com.example.demo.base.Result;
import com.example.demo.entity.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.example.demo.base.ArrayCountUtils.merge;

@RestController
@RequestMapping({"/user"})
public class UserController {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Resource
    UserMapper userMapper;

    @Resource
    QualityUserMapper qualityUserMapper;

    public UserController() {
    }

    @PostMapping({"/login"})
    public Result<?> login(@RequestBody User user) {
        QueryWrapper<User> eq = (QueryWrapper)((QueryWrapper)(new QueryWrapper()).eq("username", user.getUsername())).eq("password", user.getPassword());
        User one = (User)this.userMapper.selectOne(eq);
        if (one == null) {
            return Result.error(0, "用户名或密码错误");
        } else {
            UserVo userVo = new UserVo();
            ArrayList<String> roles = new ArrayList();
            if (one.getRole().equals(1)) {
                roles.add("ADMIN");
                userVo.setToken("admin-token");
            } else if (one.getRole().equals(2)) {
                roles.add("ADMIN");
                userVo.setToken("market-token");
            } else if (one.getRole().equals(3)) {
                roles.add("ADMIN");
                userVo.setToken("transp-token");
            } else if (one.getRole().equals(4)) {
                roles.add("ADMIN");
                userVo.setToken("farmus-token");
            } else if (one.getRole().equals(5)) {
                roles.add("ADMIN");
                userVo.setToken("firmus-token");
            }else if (one.getRole().equals(6)) {
                roles.add("ADMIN");
                userVo.setToken("surper-token");
            }
            userVo.setUsername(one.getUsername());
            userVo.setRole(roles);
            userVo.setTenantid(one.getTenantid().toString());
          //  userVo.setTenantid(one.getId().toString());
            userVo.setCertificate("certificate1234");
            return Result.success(userVo);
        }
    }

    @RequestMapping({"/logout"})
    public Result<?> logout() {
        return Result.success("退出成功！");
    }

    @RequestMapping({"/info"})
    public Result<?> userInfo(String token) {
        QueryWrapper<UserInfo> key = (QueryWrapper)(new QueryWrapper()).eq("keyword", token);
        UserInfo userInfo = (UserInfo)this.userInfoMapper.selectOne(key);
        UserInfoVo infos = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, infos);
        ArrayList<String> roles = new ArrayList();
        roles.add(userInfo.getRoles());
        infos.setRoles(roles);
        return Result.success(infos);
    }

    @PostMapping
    public Result<?> save(@RequestBody User user) {
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }

        this.userMapper.insert(user);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody User user) {
        this.userMapper.updateById(user);
        return Result.success();
    }

    @DeleteMapping({"/{id}"})
    public Result<?> update(@PathVariable Long id) {
        this.userMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping({"/{id}"})
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(this.userMapper.selectById(id));
    }

    @GetMapping({"/all"})
    public Result<?> findAll() {
        return Result.success(this.userMapper.selectList((Wrapper)null));
    }
    @GetMapping({"/quality"})
    public Result<?> quaLogin(@RequestParam String uName,
                              @RequestParam String uKey) {
        QueryWrapper<QualityUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_name", uName);
        queryWrapper.eq("u_key",uKey);
        QualityUser tmp = qualityUserMapper.selectOne(queryWrapper);
        if(tmp != null)
            return Result.success(tmp.getFirmId());
        else
            return Result.error(0,"请检查姓名或口令");
    }


    /**
     * 分页获取数据库数据
     *  管理员人员管理获取数据
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/pageAll")
    public Result<?> findPageF(@RequestParam(defaultValue = "1") String pageNum,
                                  @RequestParam(defaultValue = "10") String pageSize
                               ) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        Page<User> userPage = userMapper.selectPage(new Page<>(Integer.valueOf(pageNum), Integer.valueOf(pageSize)), wrapper);
        return Result.success(userPage);
    }

    /**
     * 租户ID查找
     *管理员人员管理根据租户ID 获取数据
     * @param tenantId
     * @return
     */

    @GetMapping("/findById")
    public Result<?> findById(
                              @RequestParam String tenantId) {
        User user =userMapper.selectById(tenantId);
        List<User> userList = new ArrayList<>();
        if (user != null) {
            userList.add(user);
            return Result.success(userList);
        }
        return Result.error(0, "没有查询到相关数据");
    }
    /**
     * 人员管理
     * 管理员根据查找用户名名称模糊查找
     *
     *@return
     */
    @GetMapping("/findByName")
    public Result<?> findByComName(@RequestParam String username) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        wrapper.like(User::getUsername, username);
        List<User> userList = userMapper.selectList(wrapper);
        if (userList.size()>0)
            return Result.success(userList);
        return Result.error(0, "没有查询到相关数据");

    }

    /**
     * 人员管理
     * 管理员添加信息
     *
     * @param tenantid
     * @param username
     * @param password
     * @param role
     * @return
     */
    @GetMapping(value = "/add")
    public Result<?> saveA(@RequestParam String tenantid,
                           @RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String role) {
        if (tenantid.isEmpty() || username.isEmpty() || password.isEmpty() || role.isEmpty() ) {
            return Result.error(0, "文本不能为空");
        }
        User user = new User(Integer.valueOf(tenantid), username,password,Integer.valueOf(role));
        userMapper.insert(user);
        return Result.success();
    }
    /**
     * 人员管理
     * 管理员根据租户号更新信息
     *
     * @param tenantid
     * @param username
     * @param password
     * @param role
     * @return
     */
    @GetMapping(value = "/update")
    public Result<?> updateById(@RequestParam String tenantid,
                                @RequestParam String username,
                                @RequestParam String password,
                                @RequestParam String role) {
       if (tenantid.isEmpty() || username.isEmpty() || password.isEmpty() || role.isEmpty() ) {
        return Result.error(0, "文本不能为空");
    }
        User user = new User(Integer.valueOf(tenantid), username,password,Integer.valueOf(role));
        userMapper.updateById(user);
        return Result.success();
    }

    /**
     * 人员管理
     * 管理员删除 人员
     *
     * @param tenantId
     * @return
     */
    @DeleteMapping("/delById")
    public Result<?> delete(
                            @RequestParam Integer tenantId) {
        int res = userMapper.deleteById(tenantId);
        if(res > 0)
            return Result.success();
        return Result.error(0, "删除失败");
    }

    public static int getFirstTwoDigits(int num) {
        return num / 100;
    }
/**
 *

 *
 * 数据可视化第一个生成租户ID饼图
 * @return
 * @return
 */

/*
    @GetMapping("/pieChatData")
    public Result<?> pieChatData() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
       //queryWrapper.eq("tenant_id", Integer.valueOf(tenantId));
        List<User> userChartList = userMapper.selectList(queryWrapper);
        Integer[] res = new Integer[userChartList.size()];
        for (int i = 0; i < userChartList.size(); i++) {
            res[i] = userChartList.get(i).getTenantid().getFirstTwoDigits
        }
        ArrayCountUtils arrayCountUtils = new ArrayCountUtils();
        List<ArrayCountUtils.Group> groups = arrayCountUtils.find(res);
        return Result.success(groups);
    }*/
  /*  *//**
     * 人员可视化
     * 多种权限用户的可视化 chatData1
     * 用户名和租户ID
     * @return
     */
    @GetMapping("/chatData1")
    public Result<?> chatData1() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        List<User> userChartList = userMapper.selectList(queryWrapper);
        List<ArrayCountUtils.BillsNums> billsNumsList = new ArrayList<>();
        for (User info : userChartList) {
            ArrayCountUtils.BillsNums billsNums = new ArrayCountUtils.BillsNums();
            billsNums.setId(info.getUsername());
            billsNums.setSums(info.getTenantid());
            billsNumsList.add(billsNums);
            billsNums = null;// 置空强制回收内存，以防数据量大内存泄露
        }
        List<ArrayCountUtils.BillsNums> res = merge(billsNumsList);
        return Result.success(res);
    }
    /**
     * 人员可视化
     * 多种权限用户的可视化 chatData2
     * 用户名和权限ID
     * @return
     */
    @GetMapping("/chatData2")
    public Result<?> chatData2() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        List<User> userChartList = userMapper.selectList(queryWrapper);
        List<ArrayCountUtils.BillsNums> billsNumsList = new ArrayList<>();
        for (User info : userChartList) {
            ArrayCountUtils.BillsNums billsNums = new ArrayCountUtils.BillsNums();
            billsNums.setId(info.getUsername());
            billsNums.setSums(info.getRole());
            billsNumsList.add(billsNums);
            billsNums = null;// 置空强制回收内存，以防数据量大内存泄露
        }
        List<ArrayCountUtils.BillsNums> res = merge(billsNumsList);
        return Result.success(res);
    }

    /**
     * 质检员获取全部数据
     *
     * @return
     */
    @GetMapping(value = "/pageAll1")
    public Result<?> findPageF(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam String tenantId) {
        LambdaQueryWrapper<QualityUser> wrapper = Wrappers.<QualityUser>lambdaQuery();
        wrapper.eq(QualityUser::getFirmId, Integer.valueOf(tenantId));
        Page<QualityUser> farmInfoPage = qualityUserMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(farmInfoPage);
    }
    /**
     * 质检员ID查找
     *企业用户管理根据质检员ID 获取数据 findById1
     * @return
     */

    @GetMapping("/findById1")
    public Result<?> findByFarmId1(@RequestParam("uId") String uId,
                                  @RequestParam String firmId) {
        QualityUser qualityUser=new QualityUser();
        qualityUser.setuId(String.valueOf(Integer.valueOf(uId)));
        qualityUser.setFirmId(Integer.valueOf(firmId));
        QualityUser tmp = qualityUserMapper.selectByMultiId(qualityUser);
        List<QualityUser> qualityUserList = new ArrayList<>();
        if (tmp != null) {
            qualityUserList.add(tmp);
            return Result.success(qualityUserList);
        }
        return Result.error(0, "没有查询到相关数据");
    }

    /**
     *  * 质检员名称查找
     *企业用户管理根据质检员名称获取数据 findById1 findByProductName1
     *
     * @param uName
     * @return
     */
    @GetMapping("/findByProductName1")
    public Result<?> findByProductName(
            @RequestParam("uName") String uName,
            @RequestParam String tenantId) {
        LambdaQueryWrapper<QualityUser> wrapper = Wrappers.<QualityUser>lambdaQuery();
        wrapper.like(QualityUser::getuName, uName) .eq(QualityUser::getFirmId,tenantId);;
        List<QualityUser> qualityUserList = qualityUserMapper.selectList(wrapper);
        if (qualityUserList.size() > 0)
            return Result.success(qualityUserList);
        return Result.error(0, "没有查询到相关数据");
    }
    /**
     * 质检员ID删除人员
     *企业用户管理根据质检员ID删除人员 delById1
     * @return
     */
    @DeleteMapping("/delById1")
    public Result<?> delete(@RequestParam String uId,
                            @RequestParam Integer  firmId) {
        QualityUser qualityUser=new QualityUser();
        qualityUser.setuId(String.valueOf(Integer.valueOf(uId)));
        qualityUser.setFirmId(Integer.valueOf( firmId));
        int res = qualityUserMapper.deleteByMultiId(qualityUser);
        if (res > 0)
            return Result.success();
        return Result.error(0, "删除失败");
    }
    /**
     * 质检员添加人员 add1
     * @param firmId
     * @param uKey
     * @param uName
     * @param uId
     * @return
     */
    @GetMapping(value = "/add1")
    public Result<?> saveE(@RequestParam Integer  firmId,
                           @RequestParam String uKey,
                           @RequestParam String uName,
                           @RequestParam String uId
    ) {
        if ( String.valueOf(firmId).isEmpty() || uKey.isEmpty() || uName.isEmpty() || uId.isEmpty() ) {
            return Result.error(0, "信息不能为空");
        }
        QualityUser qualityUser = new QualityUser(Integer.valueOf( firmId),uKey,uId,uName);
        qualityUserMapper.insert(qualityUser);
        return Result.success();
    }

    /**
     *  质检员修改人员 update1
     * @param firmId
     * @param uKey
     * @param uName
     * @param uId
     * @return
     */
    @GetMapping(value = "/update1")
    public Result<?> updateById(@RequestParam Integer  firmId,
                                @RequestParam String uKey,
                                @RequestParam String uName,
                                @RequestParam String uId
    ) {
        if ( String.valueOf(firmId).isEmpty() || uKey.isEmpty() || uName.isEmpty() || uId.isEmpty() ) {
            return Result.error(0, "信息不能为空");
        }
        QualityUser qualityUser = new QualityUser(Integer.valueOf( firmId),uKey,uId,uName);
        qualityUserMapper.updateByMultiId(qualityUser);
        return Result.success();
    }

    /**
     * 质检员可视化质检员姓名与ID可视化
     *
     * @return
     */
    @GetMapping("/chatData3")
    public Result<?> chatData3(@RequestParam int tenantId) {
        LambdaQueryWrapper<QualityUser> queryWrapper = new LambdaQueryWrapper<>();
        //筛选出ProductLog表中tenantId和传递过来的数值相等的记录。
        queryWrapper.eq(QualityUser::getFirmId, tenantId);
        List<QualityUser> qualityUserList = qualityUserMapper.selectList(queryWrapper);
        List<ArrayCountUtils.BillsNums> billsNumsList = new ArrayList<>();
        for (QualityUser log : qualityUserList) {
            ArrayCountUtils.BillsNums billsNums = new ArrayCountUtils.BillsNums();
            billsNums.setId(log.getuName());
            billsNums.setSums(Integer.valueOf(log.getuId()));
            billsNumsList.add(billsNums);
            billsNums = null;// 置空强制回收内存，以防数据量大内存泄露
        }
        List<ArrayCountUtils.BillsNums> res = merge(billsNumsList);
        return Result.success(res);
    }

    /**
     * 质检员可视化质检员姓名与租户ID可视化
     *
     * @return
     */
    @GetMapping("/chatData4")
    public Result<?> chatData4() {
        LambdaQueryWrapper<QualityUser> queryWrapper = new LambdaQueryWrapper<>();
        //筛选出ProductLog表中tenantId和传递过来的数值相等的记录。
        //queryWrapper.eq(QualityUser::getFirmId, tenantId);
        List<QualityUser> qualityUserList = qualityUserMapper.selectList(queryWrapper);
        List<ArrayCountUtils.BillsNums> billsNumsList = new ArrayList<>();
        for (QualityUser log : qualityUserList) {
            ArrayCountUtils.BillsNums billsNums = new ArrayCountUtils.BillsNums();
            billsNums.setId(log.getuName());
            billsNums.setSums(Integer.valueOf(log.getFirmId()));
            billsNumsList.add(billsNums);
            billsNums = null;// 置空强制回收内存，以防数据量大内存泄露
        }
        List<ArrayCountUtils.BillsNums> res = merge(billsNumsList);
        return Result.success(res);
    }



}

